package com.cy.utils;

import java.util.List;

/**
 * 简单SQL工具
 */
public final class SimpleSqlUtils {

    private SimpleSqlUtils(){}

    /**
     * 生成SQL
     * @param selects select列名
     * @param tables table表名
     * @param innerJoin innerJoin条件
     * @param wheres where条件
     * @param groupBy group by列名
     * @param orderBy order by列名
     * @return
     */
    public static String generateSql(List<String> selects, List<String> tables, List<String> innerJoin, List<String> wheres, List<String> groupBy, List<String> orderBy){
        StringBuilder sql = new StringBuilder();
        //SELECT语句
        for (int i = 0, size = selects.size(); i < size; i++){
            sql.append(i == 0 ? "SELECT " : ",").append(selects.get(i));
        }
        //FROM语句
        for (int i = 0, size = tables.size(); i < size; i++){
            sql.append(i == 0 ? " FROM " : ",").append(tables.get(i));
        }

        if (innerJoin != null){
            //WHERE...AND语句
            for (int i = 0, size = innerJoin.size(); i < size; i++){
                sql.append(i == 0 ? " WHERE " : " AND ").append(innerJoin.get(i));
            }
        }

        if (wheres != null){
            //WHERE...AND语句
            for (int i = 0, size = wheres.size(); i < size; i++){
                sql.append((innerJoin == null || innerJoin.size() == 0) && i == 0 ? " WHERE " : " AND ").append(wheres.get(i));
            }
        }

        if (groupBy != null){
            //GROUP BY语句
            for (int i = 0, size = groupBy.size(); i < size; i++){
                sql.append(i == 0 ? " GROUP BY " : ",").append(groupBy.get(i));
            }
        }

        if (orderBy != null){
            //ORDER BY语句
            for (int i = 0, size = orderBy.size(); i < size; i++){
                sql.append(i == 0 ? " ORDER BY " : ",").append(orderBy.get(i));
            }
        }
        return sql.toString();
    }

    /**
     * 生成IN函数SQL,如IN(?,?,?,?)
     * @param values
     * @return
     */
    public static String in(String column, Object[] values){
        StringBuilder tempSql = new StringBuilder();
        tempSql.append(column);
        tempSql.append(" IN(");
        for (int i = 0; i < values.length; i++)
            tempSql.append(i > 0 ? ","+ values[i] : values[i]);
        tempSql.append(")");
        return tempSql.toString();
    }

}
